package com.alibaba.sentinel.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.sentinel.handle.CustomerBlockHandler;
import com.alibaba.sentinel.service.SentinelService;
import com.guigu.springcloud.common.CommonResult;
import com.guigu.springcloud.entity.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/sentinel")
public class SentinelController {

    @Resource
    private SentinelService sentinelService;

    @GetMapping("/testA")
    public String getTestA() {
        return sentinelService.getTestA();
    }

    @GetMapping("/testB")
    public String getTestB() {
        return sentinelService.getTestB();

    }

    @GetMapping("/testC")
    public String getTestC() {
        return sentinelService.getTestC();
    }

    @GetMapping("/testE")
    public String getTestE() {
        System.out.println(9 / 0);
        return "测试异常数";
    }

    @GetMapping("/testHotKey")
    @SentinelResource(value = "hotKey", blockHandler = "handleHotKey")
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,
                             @RequestParam(value = "p2", required = false) String p2) {
        return "------hot key";
    }

    public String handleHotKey(String p1, String p2, BlockException e) {
        return "----sentinel fallback hot key";
    }

    //    自定义限流
    @GetMapping("/sentinelHandle")
    @SentinelResource(value = "sentinelHandle",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "sentinelHandle1")
    public String getSentinel() {
        return "----get sentinel fallback";
    }

    //CustomerBlockHandler
    @GetMapping("/customerBlockHandler")
    @SentinelResource(value = "CustomerBlockHandler", blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException2")
    public CommonResult customerBlockHandler() {
        return CommonResult.voData(200, "按客户自定义限流测试OK", new Payment(2020L, "serial003"));
    }

    @GetMapping("/hello")
    @SentinelResource(value = "hello", blockHandler = "exceptionHandler", fallback = "helloFallback")
    public String seyHello() {
        System.out.println(9 / 0);
        return "hello sentinel world";
    }

    // Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数.
    public String helloFallback(Throwable throwable) {
        return "Oops, error occurred at ";
    }

    // Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
    public String exceptionHandler(BlockException ex) {
        // Do some log here.
        return String.format("Halooooo %d", 89L);
    }
}
